package com.feicheng.house.wcpay.serviceImpl;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import com.alibaba.fastjson.JSON;
import com.feicheng.house.exception.SystemException;
import com.feicheng.house.result.ResultInfo;
import com.feicheng.house.wcpay.wechatConfig;
import com.feicheng.house.wcpay.service.PayOrderService;

import util.HttpRequest;
import weChatSdk.WXPayConstants;
import weChatSdk.WXPayUtil;

public class PayOrederServiceImpl implements PayOrderService{
	@Override
	public ResultInfo tyPay(String openid) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			map.put("mch_id", wechatConfig.MCH_ID);// 商户id
			map.put("appid", wechatConfig.APPID);// 由微信生成的应用ID，全局唯一
			map.put("out_trade_no", UUID.randomUUID().toString().replaceAll("-", ""));// 商户系统内订单号
			map.put("description", "自主健身房");// 商品描述
			map.put("notify_url", "https://weixin.qq.com/");// 通知地址
			Map<String, String> map2 = new HashMap<String, String>();
			map2.put("total", "1");// 总金额
			map2.put("currency", "CNY");// 货币类型
			map.put("amount ", map2);
			Map<String, String> map3 = new HashMap<String, String>();
			map3.put("openid", openid);
			map.put("payer", map3);
			// map集合转JSON字符串
			String josn = JSON.toJSONString(map);
			// 统一下单接口
			String unifiedorder_url = wechatConfig.UNIFIEDORDER_URL;
			// 发送请求
			String jsonStr = HttpRequest.sendPost(unifiedorder_url, josn);

			String prepay_id = "";
			if (josn.indexOf("SUCCESS") != -1) {
				Map<String, String> map4 = (Map)JSON.parse(jsonStr);
				prepay_id = (String) map4.get("prepay_id");
			}
			Map<String, String> payMap = new HashMap<String, String>();
            //二次签名
            payMap.put("appId", wechatConfig.APPID);
            payMap.put("timeStamp", WXPayUtil.getCurrentTimestamp()+"");
            payMap.put("nonceStr", WXPayUtil.generateNonceStr());
            payMap.put("signType", wechatConfig.SIGN_TYPE);
            payMap.put("package", "prepay_id=" + prepay_id);
            String paySign = WXPayUtil.generateSignature(payMap, wechatConfig.KEY, WXPayConstants.SignType.HMACSHA256);
            payMap.put("paySign", paySign);
            return ResultInfo.success(payMap);

		} catch (Exception e) {
			 throw new SystemException("");

		}

	}

}
